package com.atguigu.zy.interview.juc.single;

/**
 * @Author : Jungle
 * @Description :  懒汉式
 * DCL代码
 */
public class LazySingletonDemo {

    //1.可见性
    //2.防止重排序
    private static volatile LazySingletonDemo instance = null;

    private LazySingletonDemo() {
        System.out.println(Thread.currentThread().getName() + "\t 我是构造方法 SingletonDemo");
    }

    /**
     * 1、DCL Double Check Lock 双端检索机制 优化版本的
     * 同步代码块前后都进行一次判空
     */
    public static LazySingletonDemo getInstance() {
        if (instance == null) {
            synchronized (LazySingletonDemo.class) {
                if (instance == null) {
                    instance = new LazySingletonDemo();
                }
            }
        }
        return instance;
    }

    public static void main(String[] args) {
        //单线程情况无问题
        //System.out.println(LazySingletonDemo.getInstance()==LazySingletonDemo.getInstance());
        //System.out.println(LazySingletonDemo.getInstance()==LazySingletonDemo.getInstance());
        //System.out.println(LazySingletonDemo.getInstance()==LazySingletonDemo.getInstance());
        //并发多线程，情况发生了很大的变化
        for (int i = 1; i <= 10; i++) {
            new Thread(LazySingletonDemo::getInstance, String.valueOf(i)).start();
        }
    }
}
